package org.example.backend.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.backend.common.PageResult;
import org.example.backend.common.Result;
import org.example.backend.dto.OrderDTO;
import org.example.backend.dto.PageRequestDTO;
import org.example.backend.entity.Order;
import org.example.backend.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/order")
@Api(tags = "订单接口")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单
     *
     * @param orderDTO 订单信息
     * @param request  请求
     * @return 订单ID
     */
    @PostMapping("/create")
    @ApiOperation("创建订单")
    public Result<Long> create(@Valid @RequestBody OrderDTO orderDTO, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        orderDTO.setUserId(userId);
        try {
            Long orderId = orderService.createOrder(orderDTO);
            return Result.success(orderId);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 取消订单
     *
     * @param id 订单ID
     * @return 取消结果
     */
    @PutMapping("/cancel/{id}")
    @ApiOperation("取消订单")
    public Result<?> cancel(@PathVariable Long id) {
        try {
            orderService.cancelOrder(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 接单（分配送水员）
     *
     * @param id      订单ID
     * @param request 请求
     * @return 接单结果
     */
    @PutMapping("/take/{id}")
    @ApiOperation("接单")
    public Result<?> take(@PathVariable Long id, HttpServletRequest request) {
        Long adminId = (Long) request.getAttribute("userId");
        try {
            orderService.takeOrder(id, adminId);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 开始配送
     *
     * @param id 订单ID
     * @return 配送结果
     */
    @PutMapping("/deliver/{id}")
    @ApiOperation("开始配送")
    public Result<?> deliver(@PathVariable Long id) {
        try {
            orderService.startDelivery(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 完成订单
     *
     * @param id 订单ID
     * @return 完成结果
     */
    @PutMapping("/complete/{id}")
    @ApiOperation("完成订单")
    public Result<?> complete(@PathVariable Long id) {
        try {
            orderService.completeOrder(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新订单状态
     *
     * @param id     订单ID
     * @param status 状态
     * @return 更新结果
     */
    @PutMapping("/updateStatus/{id}")
    @ApiOperation("更新订单状态")
    public Result<?> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        try {
            orderService.updateOrderStatus(id, status);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除订单
     *
     * @param id 订单ID
     * @return 删除结果
     */
    @PostMapping("/delete/{id}")
    @ApiOperation("删除订单")
    public Result<?> delete(@PathVariable Long id) {
        try {
            orderService.deleteOrder(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询订单
     *
     * @param pageRequest 分页参数
     * @param status      状态
     * @param request     请求
     * @return 分页结果
     */
    @PostMapping("/page")
    @ApiOperation("分页查询订单")
    public Result<PageResult<Order>> page(@Valid @RequestBody PageRequestDTO pageRequest,
                                         @RequestParam(required = false) Integer status,
                                         HttpServletRequest request) {
        String role = (String) request.getAttribute("role");
        Long userId = (Long) request.getAttribute("userId");
        
        Page<Order> page = new Page<>(pageRequest.getCurrent(), pageRequest.getSize());
        
        // 根据角色过滤订单
        if ("USER".equals(role)) {
            // 用户只能查看自己的订单
            page = orderService.pageOrder(page, pageRequest.getKeyword(), status, userId, null);
        } else if ("DELIVERYMAN".equals(role)) {
            // 送水员只能查看分配给自己的订单
            page = orderService.pageOrder(page, pageRequest.getKeyword(), status, null, userId);
        } else {
            // 管理员可以查看所有订单
            page = orderService.pageOrder(page, pageRequest.getKeyword(), status, null, null);
        }
        
        return Result.success(PageResult.build(page.getTotal(), page.getSize(), page.getCurrent(), page.getRecords()));
    }

    /**
     * 获取订单详情
     *
     * @param id 订单ID
     * @return 订单信息
     */
    @GetMapping("/{id}")
    @ApiOperation("获取订单详情")
    public Result<Order> getById(@PathVariable Long id) {
        return Result.success(orderService.getOrderDetail(id));
    }
    
    /**
     * 导出订单数据
     *
     * @param keyword   关键字
     * @param status    状态
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @param request   请求
     * @param response  响应
     */
    @GetMapping("/export")
    @ApiOperation("导出订单数据")
    public void export(@RequestParam(required = false) String keyword,
                      @RequestParam(required = false) Integer status,
                      @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
                      @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
                      HttpServletRequest request,
                      HttpServletResponse response) {
        try {
            String role = (String) request.getAttribute("role");
            Long userId = (Long) request.getAttribute("userId");
            
            // 根据角色过滤订单
            if ("USER".equals(role)) {
                // 用户只能导出自己的订单
                orderService.exportOrder(response, keyword, status, userId, null, startDate, endDate);
            } else if ("DELIVERYMAN".equals(role)) {
                // 送水员只能导出分配给自己的订单
                orderService.exportOrder(response, keyword, status, null, userId, startDate, endDate);
            } else {
                // 管理员可以导出所有订单
                orderService.exportOrder(response, keyword, status, null, null, startDate, endDate);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}